<!--
 * @FilePath: /my-map-demo/src/views/chart-types/components/Heatmap.vue
 * @Author: 张文鑫
 * @Date: 2024-12-26 17:09:02
 * @Description: 
-->
<template>
  <MapBase :layers="[heatmapLayer]" />
</template>

<script setup>
import MapBase from "../MapBase.vue";
import { Heatmap as HeatmapLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import buildingData from "../data/heatMapData.json";
import GeoJSON from "ol/format/GeoJSON";
import { getCenter } from "ol/extent";
import { Point } from "ol/geom";

// 提取点数据
const features = new GeoJSON().readFeatures(buildingData, {
  dataProjection: "EPSG:4326",
  featureProjection: "EPSG:4326",
});
// 将多边形转化为中心点
const pointFeatures = features.map((feature) => {
  const geometry = feature.getGeometry();
  const center =
    geometry.getType() === "Polygon"
      ? getCenter(geometry.getExtent()) // 获取多边形中心点
      : geometry.getCoordinates(); // 如果已经是点数据，直接使用

  // 创建新的点要素
  const pointFeature = feature.clone(); // 克隆原有特性
  pointFeature.setGeometry(new Point(center)); // 替换为点
  pointFeature.set("weight", feature.get("building:levels") || 1); // 可用楼层数或其他属性赋值权重

  return pointFeature;
});

//创建热力图数据源
const buiidingVectorSource = new VectorSource({
  features: pointFeatures,
});
const heatmapLayer = new HeatmapLayer({
  source: buiidingVectorSource,
  blur: 20, // 模糊半径
  radius: 10, // 点半径
  weight: (feature) => {
    const levels = feature.get("building:levels") || 1;
    return levels / 10; // 将楼层数转化为权重
  },
});
</script>
